/* File:        	Daemon.java
* Package:			org.esi.authz.pdp.core
* Created:      	29-abr-2011
* Last Changed: 	0:08:08
* Author:       	Borja Urkizu borja.urquizu@tecnalia.com
*
*   
* History:
*  Revision 1.0.0.0  
* 
* Tecnalia Research and Innovation
*/
package com.tecnalia.comm;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;


import com.tecnalia.comm.channel.IDChannel;
import com.tecnalia.comm.channel.socket.DSocketChannelImpl;
import com.tecnalia.comm.channel.socket.IDSocketChannel;

// TODO: Auto-generated Javadoc
/**
 * The Class Daemon.
 */
public class DaemonImpl extends Thread implements IDaemon {
	    
	    public static Logger logger =  Logger.getLogger(DaemonImpl.class.getName());  
	    
	    /** The daemon socketchannel. */
	    private IDSocketChannel daemonSocketchannel = null;
	    
		private IDChannel channel = null;
	    
		/**
		 * Instantiates a new daemon.
		 */
		public DaemonImpl(String host, int port){    	
	        
	    	logger.info("Initilizazing....");
			daemonSocketchannel = new DSocketChannelImpl(host, port); 
	    	
	        //DaemonStatus.updateProperty(KEY_RUN_STATUS, STATUS_RUN_INITIALIZED);
		}

		/* (non-Javadoc)
		 * @see org.esi.authz.comm.IDaemon#run()
		 */
		@Override
		public void run() {
	  	
	    	logger.info("PDP Starting"); 	   	

	    	//Start to accept conection throught the socket channel
	    	daemonSocketchannel.start(channel);


	    }

		/* (non-Javadoc)
		 * @see org.esi.authz.comm.IDaemon#refresh()
		 */
		@Override
		public void refresh() throws Exception {
	    	logger.info("Reloading...");
	    	//Stop the socket channel and the 
	    	//this.stop();
	    	this.cleanup();


	    	//TODO: Not Complete the status impl for the DAEMON 
	    	//DaemonStatus.updateProperty(KEY_RUN_STATUS, STATUS_RUN_RUNING);
	    }

		/* (non-Javadoc)
		 * @see org.esi.authz.comm.IDaemon#cleanup()
		 */
		@Override
		public void cleanup(){

	    	logger.info("Shutdown");
	        
	    	//TODO: Not Complete the status impl for the DAEMON 
	        //DaemonStatus.updateProperty(KEY_RUN_STATUS, STATUS_RUN_NOTRUN);

	    	try {
				daemonSocketchannel.close();

	    	} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}    	
	    }

		@Override
		public IDChannel getChannel() {
			return channel;
		}

		@Override
		public void setChannel(IDChannel channelSet) {
			channel = channelSet;
		}
}
